#include <algorithm>
#include <fstream>
#include <stdexcept>

#include "tga_loader.h"

eqtest::TgaImage::TgaImage(const std::string& path):
pixel_data(NULL)
{
    std::ifstream file(path.c_str(), std::ios::binary);
    if(!file.is_open())
        throw std::runtime_error("Failed to open file.");
    
    if(!file.read((char*)&header, sizeof(header)))
        throw std::runtime_error("Tga header seems to be broken.");
    
    if(header.color_map_type != 0)
        throw std::runtime_error("Tga image with color table is not supported.");
    
    if(header.image_type != 2)
        throw std::runtime_error("Currently only uncompressed true-color tga image is supported.");
    
    if(header.image_spec.bits_per_pixel % 8 != 0)
        throw std::runtime_error("Bits per pixel is not on the byte boundary.");
    
    if(header.id_len != 0)
        file.seekg(file.tellg() + std::streampos(header.id_len));
    
    size_t pixel_data_size = size_t(header.image_spec.width) * header.image_spec.height * (header.image_spec.bits_per_pixel / 8);
    
    pixel_data.reset(new uint8_t[pixel_data_size]);
    
    if(!file.read((char*)pixel_data.get(), pixel_data_size))
        throw std::runtime_error("Tga image data broken.");
}

void eqtest::TgaImage::reverseRGB()
{
    struct RGB
    {
        uint8_t r, g, b;
    };
    struct RGBA
    {
        uint8_t r, g, b, a;
    };
    if(bits_per_pixel() == 24 && alpha_bits() == 0)
    {
        RGB *pixel = (RGB*)pixel_data.get();
        for(size_t i = 0; i < size_t(width()) * height(); ++i, ++pixel)
            std::swap(pixel->r, pixel->b);
    }
    else if(bits_per_pixel() == 32 && alpha_bits() == 8)
    {
        RGBA *pixel = (RGBA*)pixel_data.get();
        for(size_t i = 0; i < size_t(width()) * height(); ++i, ++pixel)
            std::swap(pixel->r, pixel->b);
    }
    else
        throw std::runtime_error("Unsupported pixel type for reverseRGB");
}
